﻿using System;
using System.Runtime.InteropServices;
using Data.Common;
using Data.Enum;

namespace BikeManageBusiness.logical
{
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
    public struct IDCardData
    {
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string Name; //姓名   
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)] public string Sex; //性别
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)] public string Nation; //名族
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 18)] public string Born; //出生日期
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 72)] public string Address; //住址
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 38)] public string IDCardNo; //身份证号
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string GrantDept; //发证机关
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 18)] public string UserLifeBegin; // 有效开始日期
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 18)] public string UserLifeEnd; // 有效截止日期
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 38)] public string reserved; // 保留
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 255)] public string PhotoFileName; // 照片路径
    }

    /// <summary>
    ///     新中新二代身份证逻辑操作类
    /// </summary>
    public class Dkqa16dLogical : IDisposable
    {
        #region 引用dll的函数

        /************************端口类API *************************/

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_SetMaxRFByte", CharSet = CharSet.Ansi)]
        public static extern int Syn_SetMaxRFByte(int iPort, byte ucByte, int iIfOpen);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_GetCOMBaud", CharSet = CharSet.Ansi)]
        public static extern int Syn_GetCOMBaud(int iPort, ref uint puiBaudRate);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_SetCOMBaud", CharSet = CharSet.Ansi)]
        public static extern int Syn_SetCOMBaud(int iPort, uint uiCurrBaud, uint uiSetBaud);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_OpenPort", CharSet = CharSet.Ansi)]
        public static extern int Syn_OpenPort(int iPort);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_ClosePort", CharSet = CharSet.Ansi)]
        public static extern int Syn_ClosePort(int iPort);

        /**************************SAM类函数 **************************/

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_ResetSAM", CharSet = CharSet.Ansi)]
        public static extern int Syn_ResetSAM(int iPort, int iIfOpen);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_GetSAMStatus", CharSet = CharSet.Ansi)]
        public static extern int Syn_GetSAMStatus(int iPort, int iIfOpen);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_GetSAMID", CharSet = CharSet.Ansi)]
        public static extern int Syn_GetSAMID(int iPort, ref byte pucSAMID, int iIfOpen);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_GetSAMIDToStr", CharSet = CharSet.Ansi)]
        public static extern int Syn_GetSAMIDToStr(int iPort, ref byte pcSAMID, int iIfOpen);

        /*************************身份证卡类函数 ***************************/

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_StartFindIDCard", CharSet = CharSet.Ansi)]
        public static extern int Syn_StartFindIDCard(int iPort, ref byte pucIIN, int iIfOpen);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_SelectIDCard", CharSet = CharSet.Ansi)]
        public static extern int Syn_SelectIDCard(int iPort, ref byte pucSN, int iIfOpen);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_ReadBaseMsg", CharSet = CharSet.Ansi)]
        public static extern int Syn_ReadBaseMsg(int iPort, ref byte pucCHMsg, ref uint puiCHMsgLen, ref byte pucPHMsg,
            ref uint puiPHMsgLen, int iIfOpen);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_ReadIINSNDN", CharSet = CharSet.Ansi)]
        public static extern int Syn_ReadIINSNDN(int iPort, ref byte pucIINSNDN, int iIfOpen);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_ReadBaseMsgToFile", CharSet = CharSet.Ansi)]
        public static extern int Syn_ReadBaseMsgToFile(int iPort, ref byte pcCHMsgFileName, ref uint puiCHMsgFileLen,
            ref byte pcPHMsgFileName, ref uint puiPHMsgFileLen, int iIfOpen);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_ReadIINSNDNToASCII", CharSet = CharSet.Ansi)]
        public static extern int Syn_ReadIINSNDNToASCII(int iPort, ref byte pucIINSNDN, int iIfOpen);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_ReadNewAppMsg", CharSet = CharSet.Ansi)]
        public static extern int Syn_ReadNewAppMsg(int iPort, ref byte pucAppMsg, ref uint puiAppMsgLen, int iIfOpen);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_GetBmp", CharSet = CharSet.Ansi)]
        public static extern int Syn_GetBmp(int iPort, ref byte Wlt_File);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_ReadMsg", CharSet = CharSet.Ansi)]
        public static extern int Syn_ReadMsg(int iPortID, int iIfOpen, ref IDCardData pIDCardData);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_FindReader", CharSet = CharSet.Ansi)]
        public static extern int Syn_FindReader();

        /***********************设置附加功能函数 ************************/

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_SetPhotoPath", CharSet = CharSet.Ansi)]
        public static extern int Syn_SetPhotoPath(int iOption, ref byte cPhotoPath);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_SetPhotoType", CharSet = CharSet.Ansi)]
        public static extern int Syn_SetPhotoType(int iType);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_SetPhotoName", CharSet = CharSet.Ansi)]
        public static extern int Syn_SetPhotoName(int iType);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_SetSexType", CharSet = CharSet.Ansi)]
        public static extern int Syn_SetSexType(int iType);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_SetNationType", CharSet = CharSet.Ansi)]
        public static extern int Syn_SetNationType(int iType);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_SetBornType", CharSet = CharSet.Ansi)]
        public static extern int Syn_SetBornType(int iType);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_SetUserLifeBType", CharSet = CharSet.Ansi)]
        public static extern int Syn_SetUserLifeBType(int iType);

        [DllImport("SynIDCardAPI.dll", EntryPoint = "Syn_SetUserLifeEType", CharSet = CharSet.Ansi)]
        public static extern int Syn_SetUserLifeEType(int iType, int iOption);

        #endregion

        /// <summary>
        ///     端口号
        /// </summary>
        private static int _nPort;

        public void Dispose()
        {
            GC.Collect();
        }

        /// <summary>
        ///     初始化读卡设备
        /// </summary>
        private ResultInfo<string> InitialEquipment()
        {
            var result = new ResultInfo<string>();
            try
            {
                #region 设置图片保存

                int nRet;
                var cPath = new byte[255];
                nRet = Syn_SetPhotoPath(0, ref cPath[0]);
                //stmp = Convert.ToString(System.DateTime.Now) + "  照片存放路径设置为 C:,nRet =" + Convert.ToString(nRet);

                nRet = Syn_SetPhotoType(0);
                //stmp = Convert.ToString(System.DateTime.Now) + "  照片存放格式为Bmp，nRet =" + Convert.ToString(nRet);

                nRet = Syn_SetPhotoName(1);
                //stmp = Convert.ToString(System.DateTime.Now) + "  照片保存文件名格式设置为 姓名，nRet =" + Convert.ToString(nRet);

                #endregion

                #region 设置中文显示部分字段

                Syn_SetSexType(1);
                Syn_SetNationType(1);

                #endregion
            }
            catch (Exception e)
            {
                result.ResultNumber = ResultEnum.Error;
                result.Describe = e.Message;
            }
            return result;
        }

        /// <summary>
        ///     获取身份证卡的信息
        /// </summary>
        /// <param name="port"></param>
        public ResultInfo<IDCardData> GetIdCardData()
        {
            var result = new ResultInfo<IDCardData>();
            try
            {
                var CardMsg = new IDCardData();
                int nRet, nPort;
                string stmp;
                var pucIIN = new byte[4];
                var pucSN = new byte[8];

                nPort = -1;
                var numArray = new uint[1];
                if (_nPort > 0)
                {
                    nPort = _nPort;
                }
                else
                {
                    nPort = Syn_FindReader();
                    ResultInfo<string> ie = InitialEquipment();
                    if (ie.ResultNumber == ResultEnum.Error)
                    {
                        result.ResultNumber = ie.ResultNumber;
                        result.Describe = ie.Describe;
                        return result;
                    }
                }

                if (nPort > 0)
                {
                    //if (nPort > 0x3e8)
                    //{

                    //}
                    //else
                    //{
                    //    Syn_GetCOMBaud(nPort, ref numArray[0]);
                    //}
                    if (Syn_OpenPort(nPort) == 0)
                    {
                        if (Syn_SetMaxRFByte(nPort, 80, 0) == 0)
                        {
                            nRet = Syn_StartFindIDCard(nPort, ref pucIIN[0], 0);
                            nRet = Syn_SelectIDCard(nPort, ref pucSN[0], 0);
                            nRet = Syn_ReadMsg(nPort, 0, ref CardMsg);
                            if (nRet == 0)
                            {
                                stmp = Convert.ToString(DateTime.Now) + "  姓名:" + CardMsg.Name;
                                stmp = Convert.ToString(DateTime.Now) + "  性别:" + CardMsg.Sex;
                                stmp = Convert.ToString(DateTime.Now) + "  民族:" + CardMsg.Nation;
                                stmp = Convert.ToString(DateTime.Now) + "  出生日期:" + CardMsg.Born;
                                stmp = Convert.ToString(DateTime.Now) + "  地址:" + CardMsg.Address;
                                stmp = Convert.ToString(DateTime.Now) + "  身份证号:" + CardMsg.IDCardNo;
                                stmp = Convert.ToString(DateTime.Now) + "  发证机关:" + CardMsg.GrantDept;
                                stmp = Convert.ToString(DateTime.Now) + "  有效期开始:" + CardMsg.UserLifeBegin;
                                stmp = Convert.ToString(DateTime.Now) + "  有效期结束:" + CardMsg.UserLifeEnd;
                                stmp = Convert.ToString(DateTime.Now) + "  照片文件名:" + CardMsg.PhotoFileName;
                                result.ResultNumber = ResultEnum.Success;
                                result.Describe = "获取成功";
                                result.Obj = CardMsg;
                            }
                            else
                            {
                                stmp = Convert.ToString(DateTime.Now) + "  请将身份证放在读卡器上";
                                result.ResultNumber = ResultEnum.Error;
                                result.Describe = stmp;
                                _nPort = 0;
                            }
                        }
                        else
                        {
                            result.ResultNumber = ResultEnum.Error;
                            result.Describe = string.Format("设置读取字段最大数出现错误,当前使用端口号为：{0}", nPort);
                            _nPort = 0;
                        }
                    }
                    else
                    {
                        result.ResultNumber = ResultEnum.Error;
                        result.Describe = string.Format("打开端口失败，端口号为：{0}", nPort);
                        _nPort = 0;
                    }
                }
                else
                {
                    //stmp = Convert.ToString(DateTime.Now) + "  寻找设备端口失败，请连好设备或者检查连接端口";
					stmp = "  寻找设备端口失败，请连好设备或者检查连接端口";
                    result.ResultNumber = ResultEnum.Error;
                    result.Describe = stmp;
                    _nPort = 0;
                }
            }
            catch (Exception e)
            {
                result.ResultNumber = ResultEnum.Error;
                result.Describe = e.Message;
                _nPort = 0;
            }
            GC.Collect();
            return result;
        }

        #region 备份方法

        /// <summary>
        ///     获取身份证卡的信息
        /// </summary>
        /// <param name="port"></param>
        private ResultInfo<IDCardData> GetIdCardDataxxxxx(int port)
        {
            var result = new ResultInfo<IDCardData>();
            var CardMsg = new IDCardData();
            int nRet, nPort;
            string stmp;
            var pucIIN = new byte[4];
            var pucSN = new byte[8];
            nPort = port;
            if (Syn_OpenPort(nPort) == 0)
            {
                if (Syn_SetMaxRFByte(nPort, 80, 0) == 0)
                {
                    #region 设置图片保存

                    var cPath = new byte[255];
                    nRet = Syn_SetPhotoPath(0, ref cPath[0]);
                    stmp = Convert.ToString(DateTime.Now) + "  照片存放路径设置为 C:,nRet =" + Convert.ToString(nRet);

                    nRet = Syn_SetPhotoType(0);
                    stmp = Convert.ToString(DateTime.Now) + "  照片存放格式为Bmp，nRet =" + Convert.ToString(nRet);

                    nRet = Syn_SetPhotoName(1);
                    stmp = Convert.ToString(DateTime.Now) + "  照片保存文件名格式设置为 姓名，nRet =" + Convert.ToString(nRet);

                    #endregion

                    nRet = Syn_StartFindIDCard(nPort, ref pucIIN[0], 0);
                    nRet = Syn_SelectIDCard(nPort, ref pucSN[0], 0);
                    nRet = Syn_ReadMsg(nPort, 0, ref CardMsg);
                    if (nRet == 0)
                    {
                        stmp = Convert.ToString(DateTime.Now) + "  姓名:" + CardMsg.Name;
                        stmp = Convert.ToString(DateTime.Now) + "  性别:" + CardMsg.Sex;
                        stmp = Convert.ToString(DateTime.Now) + "  民族:" + CardMsg.Nation;
                        stmp = Convert.ToString(DateTime.Now) + "  出生日期:" + CardMsg.Born;
                        stmp = Convert.ToString(DateTime.Now) + "  地址:" + CardMsg.Address;
                        stmp = Convert.ToString(DateTime.Now) + "  身份证号:" + CardMsg.IDCardNo;
                        stmp = Convert.ToString(DateTime.Now) + "  发证机关:" + CardMsg.GrantDept;
                        stmp = Convert.ToString(DateTime.Now) + "  有效期开始:" + CardMsg.UserLifeBegin;
                        stmp = Convert.ToString(DateTime.Now) + "  有效期结束:" + CardMsg.UserLifeEnd;
                        stmp = Convert.ToString(DateTime.Now) + "  照片文件名:" + CardMsg.PhotoFileName;
                        result.ResultNumber = ResultEnum.Success;
                        result.Describe = "获取成功";
                        result.Obj = CardMsg;
                    }
                    else
                    {
                        stmp = Convert.ToString(DateTime.Now) + "  读取身份证信息错误";
                        result.ResultNumber = ResultEnum.Error;
                        result.Describe = stmp;
                    }
                }
            }
            else
            {
                stmp = Convert.ToString(DateTime.Now) + "  打开端口失败";
                result.ResultNumber = ResultEnum.Error;
                result.Describe = stmp;
            }
            return result;
        }

        #endregion
    }
}